var gCodeLine_obj = [];
//mqtt接收数据
var LINE_NUMBER = [];
var dataSize = 0;
var dataBuffer = 5000; //缓冲区
//  var ydata1=[];
//  var ydata2=[];
var initData = [];
var updateData = [];
var yAxisLabel;
var yAxisLabels = [];
var html = '';
var loop = 0;
var macsn = $('#macsn').text();

var SampleChannel,
  Custom,
  TmpIDS,
  IDS = [],
  map = {},
  TopicDataMap = {},
  flag,
  Custom_b,
  sampleDataIndex = []; //采样通道索引
var modeljsonMap = {};

$(document).ready(function() {
  init_mqtt();
});
var myChart = echarts.init(document.getElementById('echart_show'));

// timeTicket=setInterval(function(){
// 	myChart.setOption({
//         legend:{data:yAxisLabels},
// 		xAxis:{data:gCodeLine_obj},
// 		series:initData1
// 	});
// },1000)

//设置图标配置项
var option = {
  //
  backgroundColor: 'rgba(0,0,0,0.45)',
  color: [
    '#87cefa',
    '#da70d6',
    '#32cd32',
    '#6495ed',
    '#ff69b4',
    '#ba55d3',
    '#cd5c5c',
    '#ffa500',
    '#40e0d0',
    '#1e90ff',
    '#ff6347',
    '#7b68ee',
    '#00fa9a',
    '#ffd700',
    '#6699FF',
    '#ff6666',
    '#3cb371',
    '#b8860b',
    '#30e0e0',
  ],
  tooltip: {
    trigger: 'axis',
    //  textStyle:{ color:['#87cefa','#da70d6','#32cd32','#6495ed'] },
    axisPointer: {
      // type: 'cross',
      animation: false,
      label: {
        backgroundColor: '#505765',
      },
    },
    formatter: function(params) {
      return TooltipFormatter(params);
      //  return params[2].name + '<br />' + params[2].value;
    },
  },
  //        toolbox:{
  //		     left: 'center',
  //             itemSize: 45,
  //             showTitle:true,
  //             top: 55,
  //
  //             feature: {
  //              dataZoom: {
  //                yAxisIndex: 'none'
  //               },
  //                restore: {}
  //              },
  //            iconStyle:{
  //                 borderColor: "#666",
  //                 borderWidth: 100
  //                 },
  //        },
  addDataAnimation: false,
  animation: false,
  legend: {
    //data:['指令位置','实际位置'],
    data: yAxisLabels,
    itemWidth: 40,
    itemHeight: 20,
    show: true,
    textStyle: {
      color: '#fff',
      fontSize: 20,
    },
  },
  // 网格
  grid: {
    right: '13%',
    // width: {totalWidth} - x - x2,
    // height: {totalHeight} - y - y2,
    backgroundColor: 'rgba(125,125,6,0.86)',
    borderWidth: 10,
    borderColor: '#666',
  },
  //color: 'green',
  xAxis: {
    type: 'category',
    name: 'G代码行号',
    boundaryGap: false,
    nameTextStyle: {
      fontSize: 20,
    },
    axisLine: {
      onZero: false,
      lineStyle: {
        color: '#fff',
        width: 2,
      },
    },
    //color:"#060",
    data: gCodeLine_obj,
  },
  yAxis: {
    boundaryGap: [0, '100%'],
    name: '采样值',
    type: 'value',
    splitLine: {
      show: false,
    },
    axisLine: {
      lineStyle: {
        color: '#fff',
        width: 2,
      },
    },
    nameTextStyle: {
      fontSize: 20,
    },
  },
  series: initData,
};

function TooltipFormatter(params) {
  var seriesNames = [];
  var formateStrings = [];
  var formateString = '';
  if (params.length > 0) {
    // formateStrings.push("行号："+data[0].name);
    var formateStrings = '行号：' + params[0].name;
    for (var i = 0; i < params.length; i++) {
      if (params[i].name != '') {
        formateStrings +=
          '<div class="circle"><span style="background:' +
          params[i].color +
          '"></span>' +
          params[i].seriesName +
          ' : ' +
          params[i].value +
          '</div>';
      }
    }
    //                 console.log(formateStrings)
    return formateStrings;
  }
}

// Generate four random hex digits.
function S4() {
  return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
// Generate a pseudo-GUID by concatenating random hexadecimal.
function guid() {
  return S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4();
}

function init_mqtt() {
  var hostname = 'mqtt.hzncc.cn';
  //'10.1.20.93', //'192.168.1.2',
  (port = 443),
    (clientId = 'client-hzsk' + guid()),
    (timeout = 5),
    //        keepAlive = 100,
    (keepAliveInterval = 10),
    (cleanSession = false),
    (ssl = false),
    // userName = 'mao2080',
    // password = '123',
    // diviceID = macsn;
    //      diviceID = "26AF1B9E3FF398E",
    (ConnectNO = 0),
    (SampleChannel = ''),
    (sampleFlag = 5),
    (sampleData = []),
    (getMessage = 0),
    (checkAxis = ''),
    (yAxisData = {}),
    (yAxisLabels = []),
    (gCodeLine_obj = []);
  probe_response_topic = 'Probe/Query/Response/' + macsn;
  probe_request_topic = 'Probe/Query/Request/' + macsn;
  //sample_topic = 'Sample/' + diviceID + '/'+SampleChannel;
  client = new Paho.MQTT.Client(hostname, port, clientId);
  //建立客户端实例
  client.onConnectionLost = onConnectionLost;
  //注册连接断开处理事件
  client.onMessageArrived = onMessageArrived;
  client.connect({ onSuccess: onConnect, useSSL: true });

  //连接服务器并注册连接成功处理事件
  function onConnect() {
    s = '{连接服务器并注册连接成功--time:' + new Date().Format('yyyy-MM-dd hh:mm:ss') + ', onConnected()}';
    client.subscribe(probe_response_topic);
    message = new Paho.MQTT.Message(probe_request_topic);
    message.destinationName = probe_request_topic;
    client.send(message);
    console.log(s);
    console.log(probe_request_topic);
  }

  //注册消息接收处理事件
  function onConnectionLost(responseObject) {
    console.log(responseObject);
    s = '{接收处理事件--time:' + new Date().Format('yyyy-MM-dd hh:mm:ss') + ', onConnectionLost()}';
    console.log(s);

    if (responseObject.errorCode !== 0) {
      console.log('onConnectionLost:' + responseObject.errorMessage);
      console.log('连接已断开');
    }
  }

  function onMessageArrived(message) {
    console.log(message);
    var json_message = jQuery.parseJSON(message.payloadString);

    if (message.destinationName == probe_response_topic && ConnectNO == 0) {
      handle_model_json(json_message);
    } else if (message.destinationName == sample_topic) {
      handle_sample_json(json_message);
    }
  }
}

//处理model文件
function handle_model_json(json_message) {
  formatModel(json_message.probe);
  if (SampleChannel != '') {
    //采样ID存在，订阅采样数据
    sample_topic = 'Sample/' + macsn + '/' + SampleChannel;
    client.subscribe(sample_topic);
    ConnectNO = 1;
  }
}
var XAxisTopics = [];
function handle_sample_json(json_message) {
  if (json_message.id == SampleChannel && json_message.data.length != null) {
    //比较累计数据和缓冲区大小
    for (var i = 0; i < sampleDataIndex.length; i++) {
      //匹配采样通道数据
      TopicDataMap[sampleDataIndex[i]] = json_message.data[i].data;
      //寻找采样通道数据中G代码行号
      if (sampleDataIndex[i].indexOf('LINE_NUMBER') != -1) {
        LINE_NUMBER = json_message.data[i].data;
        dataSize = LINE_NUMBER.length;
      }
    }

    //X轴
    for (var a in axisTopicsMap) {
      if ($('#' + a).hasClass('btn-select-chart-active')) {
        //切换轴
        if (initData.length == 0) {
          axisTopicsMap[a].forEach(function(topic) {
            //取topic name
            yAxisLabel = topic.split(':')[topic.split(':').length - 1];
            yAxisLabels.push(yAxisLabel);
            //初始化图标参数
            initYaxisData();
            //初始化更新图标参数
            updateYaxisData();
          });
          XAxisTopics = axisTopicsMap[a];
          //初始化图表
          myChart.setOption(option, true);
        } else {
          addData();
          if (gCodeLine_obj.length >= dataBuffer) {
            shiftData();
          }
          //                     console.log("g" +dataSize);
          //                   console.log("init" + updateData[0].data.length);
        }
      }
    }
    //   option.series=updateData;
    //更新图
    myChart.setOption({
      legend: { data: yAxisLabels },
      xAxis: { data: gCodeLine_obj },
      series: updateData,
    });
  }
}

function addData() {
  for (var i = 0; i < dataSize; i++) {
    gCodeLine_obj.push(LINE_NUMBER[i]);
    for (var j = 0; j < XAxisTopics.length; j++) {
      updateData[j].data.push(TopicDataMap[XAxisTopics[j]][i]);
    }
  }
}

function shiftData() {
  for (var i = 0; i < dataSize; i++) {
    gCodeLine_obj.shift();
    for (var j = 0; j < XAxisTopics.length; j++) {
      updateData[j].data.shift();
    }
  }
}

function initYaxisData() {
  var arr = {};
  arr.name = yAxisLabel;
  arr.type = 'line';
  arr.smooth = true;
  arr.symbol = 'none';
  arr.stack = 'a';
  arr.data = [];
  initData.push(arr);
  return initData;
}

function updateYaxisData() {
  var arr = {};
  arr.name = yAxisLabel;
  arr.data = [];
  updateData.push(arr);
  return updateData;
}

var select = 0;
//点击轴事件
function AxisClick(t) {
  $('.btn-time-chart').removeClass('btn-select-chart-active');
  var index = $(t)[0].innerHTML;
  if (index != null) {
    var id = index.substring(2);
    $('#' + id).addClass('btn-select-chart-active');
  }
  initData = [];
  updateData = [];
  yAxisLabels = [];
  gCodeLine_obj = [];

  // console.log(index);
}

function showAxisButtons() {
  for (var axisTopic in axisTopicsMap) {
    showAxisLabel(axisTopic);
  }
}

function formatModel(modelData) {
  // console.log("modelData: "+modelData.devices);
  //basic info
  formatBasicInfo(modelData);

  if (modelData.configs != null) {
    modelData.configs.forEach(function(modelConfigData) {
      formatModelConfigData(modelConfigData);
    });
    //  console.log("formatModelConfigData"+JSON.stringify(obj));
    // for (var i = 0; i < modelData.configs.length(); i ++){
    //     var modelConfigData = modelData.configs[i];
    //
    // }
  }
  // console.log(Custom);
  //devices
  if (modelData.devices != null) {
    modelData.devices.forEach(function(deviceData) {
      formatDevice(deviceData);
    });
  }
  if (map != null) {
    var sampleIDS = map[SampleChannel];
    sampleIDS.forEach(function(mapData) {
      formatmapData(mapData);
    });

    // console.log(sampleDataIndex);
    //转化轴和topic对应表
    init_axis_topics_map(sampleDataIndex);
    showAxisButtons();
  }
  //      .log(map);
}

var axisTopicsMap = {};
function init_axis_topics_map(sampleDataIndex) {
  sampleDataIndex.forEach(function(sampleData) {
    var index = sampleData.indexOf('#');
    if (index != -1) {
      var axisName = sampleData.substring(index + 1, index + 2);
      if (!axisTopicsMap.hasOwnProperty(axisName)) {
        axisTopicsMap[axisName] = [];
      }
      var topicList = axisTopicsMap[axisName];
      topicList.push(sampleData);
    }
  });
  //console.log(axisTopicsMap);
}
function formatmapData(mapData) {
  sampleDataIndex.push(map[mapData]);
}
//device
function formatDevice(deviceData) {
  //basic info
  formatDeviceBasicInfo(deviceData);

  //configs
  if (deviceData.configs != null) {
    deviceData.configs.forEach(function(deviceConfigData) {
      formatDeviceConfig(deviceConfigData);
    });
  }

  //right
  // //dataItems
  if (deviceData.dataItems != null) {
    deviceData.dataItems.forEach(function(dataItemData) {
      formatDeviceDataItem(dataItemData);
      //Custom=Custom+dataItemData["type"];
    });
  }

  // //components
  if (deviceData.components != null) {
    deviceData.components.forEach(function(componentData) {
      formatComponent(componentData);
    });
  }
}
//
function formatComponent(componentData) {
  //info
  formatComponentBasicInfo(componentData);
  //Custom=Custom+":"+ componentData.type+"#"+componentData.number;
  //configs
  if (componentData.configs != null) {
    componentData.configs.forEach(function(configData) {
      formatComponentConfig(configData);
    });
  }
  //dataitems
  if (componentData.dataItems != null) {
    componentData.dataItems.forEach(function(dataItemData) {
      formatComponentDataItem(dataItemData);
    });
  }
  //component
  if (componentData.components == null) {
    return;
  }
  componentData.components.forEach(function(componentTempData) {
    formatComponent(componentTempData);
  });
}

function formatBasicInfo(_data) {
  //初始化 Custom
  map[_data.id] = _data.type;
  Custom = _data.type; //NC_LINK_ROOT
}
function formatDeviceBasicInfo(_data) {
  map[_data.id] = Custom + ':' + _data.type;
  Custom_b = map[_data.id];
}
function formatComponentBasicInfo(_data) {
  if (_data.type == 'AXIS') {
    map[_data.id] = Custom_b + ':' + _data.type + '#' + _data.number;
  } else if (_data.type == 'CONTROLLER') {
    map[_data.id] = Custom_b + ':' + _data.type;
  } else {
    map[_data.id] = flag + ':' + _data.type;
  }
  flag = map[_data.id];
}

function formatModelConfigData(_data) {
  map[_data.id] = Custom + ':' + _data['type'];
}

function formatDeviceDataItem(_data) {
  map[_data.id] = Custom_b + ':' + _data['type'];
}

function formatComponentDataItem(_data) {
  if (_data['commanded'] == true) {
    map[_data.id] = flag + ':' + _data['type'] + ':Commanded' + ':' + _data['name'];
  } else {
    map[_data.id] = flag + ':' + _data['type'] + ':' + _data['name'];
  }
}

function formatDeviceConfig(_data) {
  if (_data['type'] == 'SAMPLE_CHANNEL') {
    //取采样通道ID SampleChannel
    SampleChannel = _data['id'];
    TmpIDS = _data['ids'];
    //取采样ID集合
    for (var id in TmpIDS) {
      IDS.push(TmpIDS[id].id);
    }
    map[_data['id']] = IDS;
    //console.log(IDS)
    IDS = [];
  }
}

function formatComponentConfig(_data) {
  if (_data['type'] == 'SAMPLE_CHANNEL') {
    //取采样通道ID SampleChannel
    SampleChannel = _data['id'];
    TmpIDS = _data['ids'];
    //取采样ID集合
    for (var id in TmpIDS) {
      IDS.push(TmpIDS[id].id);
    }
    map[_data['id']] = IDS;
    //console.log(IDS)
    IDS = [];
  }
  //  flag=flag+":"+ _data["type"];
}
function showAxisLabel(axisTopic) {
  if (loop == 0) {
    html =
      html +
      [
        '<div class="btn-time-chart btn-select-chart-active"',
        'id=' + axisTopic,
        ' onclick=AxisClick(this)>',
        '轴 ' + axisTopic,
        '</div>',
      ].join('');
    $('.tab-select').html(html);
  }
  if (loop == 1) {
    html =
      html +
      ['<div class="btn-time-chart"', 'id=' + axisTopic, ' onclick=AxisClick(this)>', '轴 ' + axisTopic, '</div>'].join(
        ''
      );
    $('.tab-select').html(html);
  }
  loop = 1;
}
Date.prototype.Format = function(fmt) {
  //author: meizz
  var o = {
    'M+': this.getMonth() + 1, //月份
    'd+': this.getDate(), //日
    'h+': this.getHours(), //小时
    'm+': this.getMinutes(), //分
    's+': this.getSeconds(), //秒
    'q+': Math.floor((this.getMonth() + 3) / 3), //季度
    S: this.getMilliseconds(), //毫秒
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp('(' + k + ')').test(fmt))
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
  return fmt;
};
